from flask import jsonify, request
from datetime import datetime
from decimal import Decimal
from approval_service.approval.service.approval_service import ApprovalService
from commons.controller.base_controller import BaseController
from commons.entity.po.approval import Approval


class ApprovalController(BaseController):
    def __init__(self):
        self.approval_service = ApprovalService()

    def get_approval_by_id(self):
        """
        根据审批状态ID获取审批状态信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        approval_id = data.get("approvalId")

        return BaseController.get_success_response(self, self.approval_service.get_approval_by_approval_id(approval_id))

    def get_approval_by_travel_id(self):
        """
        根据审批状态ID获取审批状态信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        travel_id = data.get("travelId")

        return BaseController.get_success_response(self, self.approval_service.get_by_travel_id(travel_id))

    def update_approval_by_travel_id(self):
        """
        根据 travelId 更新审批状态（经理审批状态为 0）。
        """
        try:
            # 从请求体中获取 travelId 参数
            data = request.get_json()
            travel_id = data.get("travelId")

            # 如果没有传递 travelId，返回错误响应
            if not travel_id:
                return BaseController.get_error_response(self, "Missing travelId", 400)

            # 获取审批信息
            approval = self.approval_service.get_approval_by_travel_id(
                travel_id)

            # 如果没有找到对应的审批记录，返回错误响应
            if not approval:
                return BaseController.get_error_response(self, f"Approval record not found for travelId {travel_id}",
                                                         404)

            # 更新审批状态中的 "ReimbursementApprovalMa" 为 0
            approval.set_reimbursement_approval_ma(0)

            # 更新审批记录
            updated = self.approval_service.update_approval_by_approval_id(
                approval, approval.approval_id)

            # 如果更新失败，返回错误响应
            if not updated:
                return BaseController.get_error_response(self, "Failed to update approval", 500)

            # 返回成功响应
            return BaseController.get_success_response(self, {"message": "Approval status updated successfully"})

        except Exception as e:
            # 捕获任何异常并返回错误响应
            return BaseController.get_error_response(self, str(e), 500)

    # 获取出差申请分页数据
    def get_travel_apply(self):
        """
        分页查询出差申请
        param userId: 工号
        param pageNo: 页码
        param pageSize: 页大小
        :return: 分页结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        page_no = data.get('pageNo')
        page_size = data.get('pageSize')

        # 返回成功响应，调用approval_service获取数据
        return BaseController.get_success_response(self,
                                                   self.approval_service.get_travel_apply(user_id, page_no, page_size))

    # 审批出差申请
    def approve_travel_apply(self):
        """
        审批出差申请
        param userId: 工号
        param approvalId: 审批ID
        param status: 审批状态
        param travelRejection: 出差拒绝原因
        :return: 审批结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        approval_id = data.get('approvalId')
        status = data.get('status')
        travel_rejection = data.get('travelRejection')

        # 调用审批服务进行审批，并返回对应的响应
        if self.approval_service.approve_travel_apply(user_id, approval_id, status, travel_rejection):
            return BaseController.get_success_response(self, None)
        return BaseController.get_server_error_response(self, None)

    # 获取预支申请分页数据
    def get_advance_apply(self):
        """
        分页查询预支申请
        param userId: 工号
        param pageNo: 页码
        param pageSize: 页大小
        :return: 分页结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        page_no = data.get('pageNo')
        page_size = data.get('pageSize')

        # 返回成功响应，调用approval_service获取数据
        return BaseController.get_success_response(self,
                                                   self.approval_service.get_advance_apply(user_id, page_no, page_size))

    # 审批预支申请
    def approve_advance_apply(self):
        """
        审批预支申请
        param userId: 工号
        param approvalId: 审批ID
        param payment: 支付金额
        param status: 审批状态
        param advanceRejection: 拒绝原因
        :return: 审批结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        approval_id = data.get('approvalId')
        payment = data.get('payment')
        status = data.get('status')
        advance_rejection = data.get('advanceRejection')

        # 调用审批服务进行审批，并返回对应的响应
        if self.approval_service.approve_advance_apply(user_id, approval_id, payment, status, advance_rejection):
            return BaseController.get_success_response(self, None)
        return BaseController.get_server_error_response(self, None)

    # 获取报销申请分页数据
    def get_reimbursement_apply_ma(self):
        """
        分页查询报销申请（管理端）
        param userId: 工号
        param pageNo: 页码
        param pageSize: 页大小
        :return: 分页结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        page_no = data.get('pageNo')
        page_size = data.get('pageSize')

        # 返回成功响应，调用approval_service获取数据
        return BaseController.get_success_response(self,
                                                   self.approval_service.get_reimbursement_apply_ma(
                                                       user_id, page_no, page_size))

    # 审批报销申请（管理端）
    def approve_reimbursement_apply_ma(self):
        """
        审批报销申请（管理端）
        param userId: 工号
        param reimbursementId: 报销ID
        param approvalId: 审批ID
        param status: 审批状态
        param reimbursementRejection: 拒绝原因
        :return: 审批结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        reimbursement_id = data.get('reimbursementId')
        approval_id = data.get('approvalId')
        status = data.get('status')
        reimbursement_rejection = data.get('reimbursementRejection')

        # 调用审批服务进行审批，并返回对应的响应
        if self.approval_service.approve_reimbursement_apply_ma(
                user_id, reimbursement_id, approval_id, status, reimbursement_rejection):
            return BaseController.get_success_response(self, None)
        return BaseController.get_server_error_response(self, None)

    # 获取报销申请分页数据（财务端）
    def get_reimbursement_apply_fi(self):
        """
        分页查询报销申请（财务端）
        param userId: 工号
        param pageNo: 页码
        param pageSize: 页大小
        :return: 分页结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        page_no = data.get('pageNo')
        page_size = data.get('pageSize')

        # 返回成功响应，调用approval_service获取数据
        return BaseController.get_success_response(self,
                                                   self.approval_service.get_reimbursement_apply_fi(user_id, page_no,
                                                                                                    page_size))

    # 审批报销申请（财务端）
    def approve_reimbursement_apply_fi(self):
        """
        审批报销申请（财务端）
        param userId: 工号
        param reimbursementId: 报销ID
        param approvalId: 审批ID
        param payment: 支付金额
        param status: 审批状态
        param reimbursementRejection: 拒绝原因
        :return: 审批结果
        """
        data = request.get_json()
        user_id = data.get('userId')
        reimbursement_id = data.get('reimbursementId')
        approval_id = data.get('approvalId')
        payment = data.get('payment')
        status = data.get('status')
        reimbursement_rejection = data.get('reimbursementRejection')

        # 调用审批服务进行审批，并返回对应的响应
        if self.approval_service.approve_reimbursement_apply_fi(user_id, reimbursement_id, approval_id, payment, status,
                                                                reimbursement_rejection):
            return BaseController.get_success_response(self, None)
        return BaseController.get_server_error_response(self, None)


    def add_approval(self):
        user_id = request.form.get('userId')
        advance_payment = request.form.get('advancePayment')

        if not user_id or not advance_payment:
            return jsonify({"status": "error", "message": "Missing parameters"}), 400

        try:
            advance_payment = Decimal(advance_payment)
        except ValueError:
            return jsonify({"status": "error", "message": "Invalid advancePayment value"}), 400

        print(advance_payment)

        if advance_payment > 0:
            approval = Approval(
                travel_approval = 0,
                advance_approval = 0,
                reimbursement_approval_ma = 0,
                reimbursement_approval_fi = 0,
                travel_rejection = None,
                advance_rejection = None,
                reimbursement_rejection_ma = None,
                reimbursement_rejection_fi = None,
                travel_id = None,
                user_id = user_id
            )
        else:
            approval = Approval(
                travel_approval=0,
                advance_approval=3,
                reimbursement_approval_ma=0,
                reimbursement_approval_fi=0,
                travel_rejection=None,
                advance_rejection=None,
                reimbursement_rejection_ma=None,
                reimbursement_rejection_fi=None,
                travel_id=None,
                user_id=user_id
            )


        return BaseController.get_success_response(self.approval_service.add(approval))

